//
//  JMGrabChipsVController.m
//  jiMuOperate
//
//  Created by 翁仪 on 16/5/4.
//  Copyright © 2016年 jinXinFengLi. All rights reserved.
//

#import "JMGrabChipsVController.h"
#import "JMGrabChipsCell.h"
#import "robChipModel.h"
#import "JMReleaseStrVController.h"
#import "JMNickNameVController.h"
#import "JMReleaseStrVController.h"
#import "MJRefresh.h"
#import "MJRefreshFooterView.h"
#import "voteModel.h"
@interface JMGrabChipsVController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)NSMutableArray *robChips;
@property(nonatomic,strong)JMGrabChipsCell *GrabChipsCell;
@property(nonatomic,strong)robChipModel *robChip;
@end

@implementation JMGrabChipsVController
{
    UIImageView *_headerImage;
    UIView *_buttonView;
    UITableView *_tabelView;
    UIRefreshControl *_refreshControl;
//    默认
     UIButton *_fautBut;
//    胜率
     UIButton *_winRateBut;
//    投票人数
     UIButton *_codeNuBut;
//    下拉刷新
    UIRefreshControl *_fresh;
//    上拉刷新
    MJRefreshFooterView *_footer;

}
- (void)viewDidLoad {
    [super viewDidLoad];
    //    隐藏导航条
    HIDDENNAV(YES);
    
    //    添加头部的image
    [self addheaderview];
    //    添加加载按钮的视图
    [self addbuttonview];
    //    添加tabelview
    [self addtabelview];
//    //设置cell的一些属性
    [self setTabelViewcell];
    //    下拉刷新
    [self setDonwRefresh];
//    //    上拉加载
//    [self setupRefresh];

    
}
//懒加载数组
-(NSArray *)robChips{

    
    if (_robChips==nil) {
        
        NSString *strurl = [NSString stringWithFormat:@"api/Strategy/GetStrategyList?Token=%@&page=%@&pageSize=%@&Sort=%@",@"oxpDpszxtm69VMqWnPfPQLNhoQPbgHsWGgwBxoZ9EKW9qnu2XwS%2fJGfD2VFR3Kg3",@"1",@"5",@""];

        [self loadDatastrUrl:strurl];

           }

    return _robChips;
}
-(void)loadDatastrUrl:(NSString *)strUrl{

//
    NSArray *arrayR = @[@"",strUrl,@"GET"];
    [Request startRequestWithArray:arrayR FinishedBlock:^(NSData *data) {
        if (data) {
            //请求成功，解析json数据
            NSDictionary *dict = [JMData dictAndTestData:data];
            
            NSMutableArray *array =dict[@"data"];

            NSMutableArray *temparray = [NSMutableArray array];
 
            for (NSDictionary *dict in array) {
                
              //  字典转模型
                    robChipModel *robChip = [robChipModel robChipWithDict:dict];
                    [temparray addObject:robChip];

                            }
            _robChips = temparray;
            
            [_tabelView reloadData];

        }
    } FailBlock:^(NSString *string) {
        NSLog(@"加载失败－－－－－－－");
    }];
//    回到主线程
//    dispatch_async(dispatch_get_main_queue(), ^{
//
//            });
}
//设置cell的一些属性
-(void)setTabelViewcell{
//         _tabelView.editing = NO;
    _tabelView.userInteractionEnabled=YES;
  
    _tabelView.rowHeight = 100;
    _tabelView.rowHeight = [ToolViewAndData autoLayoutBackHeight: _tabelView.rowHeight];
    _tabelView.separatorStyle=UITableViewCellSeparatorStyleNone;
}
//在view上添加视图
-(void)addheaderview{
    
    UIImageView *imageview  = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 125)];
    _headerImage = imageview;
    imageview.image = [UIImage imageNamed:@"bg_rob_to_raise"];

    
    UIButton *backBut  =[[UIButton alloc] initWithFrame:CGRectMake(0, 16, 40, 40)];
    [backBut addTarget:self action:@selector(backBut) forControlEvents:UIControlEventTouchUpInside];

    [backBut setImage: [UIImage imageNamed:@"aut_ico_back"] forState:UIControlStateNormal];
   UILabel *label =  [ARC createLabelWithFrame:CGRectMake(0,16, 320, 44) Font:18 Text:@"松果抢筹"];
    [imageview addSubview:label];
    [self.view addSubview:imageview];
    [self.view addSubview:backBut];

    imageview.frame = [ToolViewAndData MyAutoLayout:imageview];
    backBut.frame = [ToolViewAndData MyAutoLayout:backBut];
     label.frame = [ToolViewAndData MyAutoLayout:label];
};
-(void)addbuttonview{
    
 
    CGFloat viewY = 125;
    CGFloat viewW = 320;
    CGFloat viewH = 40;
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0,  viewY, viewW, viewH)];
//    view.frame = [ToolViewAndData MyAutoLayout:view];

    _buttonView = view;
    view.backgroundColor = RGB(255, 255, 255);
    
    CGFloat fautbutX = 25;
    CGFloat fautbutY = 6 ;
    CGFloat fautbutW = 50;
    CGFloat fautbutH = 30 ;
    UIButton *fautbut= [UIButton buttonWithType:UIButtonTypeCustom];
    fautbut.frame =CGRectMake(fautbutX, fautbutY, fautbutW, fautbutH);
    [fautbut addTarget:self action:@selector(faut:) forControlEvents:UIControlEventTouchUpInside ];
    [fautbut setTitle:@"默认" forState:UIControlStateNormal];
    [fautbut setTitleColor:RGB(120, 120, 120) forState:UIControlStateNormal];
    [fautbut setTitleColor:RGB(0, 188, 236) forState:UIControlStateSelected];
    fautbut.titleLabel.font = [UIFont systemFontOfSize: 16.0];
    _fautBut = fautbut;
    fautbut.selected = YES;
    [view addSubview:fautbut];
    
    
    CGFloat planGainsW = fautbutW;
    CGFloat planGainsX = (320-planGainsW)/2-15;
    CGFloat planGainsH = fautbutH ;
    UIButton *planGains= [UIButton buttonWithType:UIButtonTypeCustom];
    planGains.frame =CGRectMake(planGainsX, fautbutY, planGainsW, planGainsH);
    [planGains addTarget:self action:@selector(winRate:) forControlEvents:UIControlEventTouchUpInside ];
    [planGains setTitle:@"胜率" forState:UIControlStateNormal];
    [planGains setTitleColor:RGB(120, 120, 120) forState:UIControlStateNormal];
    [planGains setImage:[UIImage imageNamed:@"jiantou2"] forState:UIControlStateNormal];
    [planGains setImage:[UIImage imageNamed:@"jiantou-1"] forState:UIControlStateSelected];
    [planGains setTitleColor:RGB(0, 188, 236) forState:UIControlStateSelected];
    [planGains setImageEdgeInsets:UIEdgeInsetsMake(0, 55, 0, 0)];
//    [planGains setTitleEdgeInsets:UIEdgeInsetsMake(0, -5, 0, 0)];

      planGains.titleLabel.font = [UIFont systemFontOfSize: 16.0];
    _winRateBut = planGains;
    [view addSubview:planGains];
    
    CGFloat codeNuW = fautbutW+20;
    CGFloat codeNuX = 320-codeNuW-fautbutX-8;
    CGFloat codeNuH = fautbutH ;
    UIButton *codeNu= [UIButton buttonWithType:UIButtonTypeCustom];
    codeNu.frame =CGRectMake(codeNuX, fautbut.frame.origin.y, codeNuW, codeNuH);
    [codeNu addTarget:self action:@selector(codeNu:) forControlEvents:UIControlEventTouchUpInside ];
    [codeNu setTitle:@"投票数" forState:UIControlStateNormal];
    [codeNu setTitleColor:RGB(120, 120, 120) forState:UIControlStateNormal];
    [codeNu setImage:[UIImage imageNamed:@"jiantou2"] forState:UIControlStateNormal];
    [codeNu setImage:[UIImage imageNamed:@"jiantou-1"] forState:UIControlStateSelected];
    [codeNu setTitleColor:RGB(0, 188, 236) forState:UIControlStateSelected];
     codeNu.titleLabel.font = [UIFont systemFontOfSize: 16.0];
    [codeNu setImageEdgeInsets:UIEdgeInsetsMake(0, 75, 0, 0)];
//    [codeNu setTitleEdgeInsets:UIEdgeInsetsMake(0, 20, 0, 0)];

    _codeNuBut = codeNu;
    
    fautbut.frame = [ToolViewAndData MyAutoLayout:fautbut];
        planGains.frame = [ToolViewAndData MyAutoLayout:planGains];
        codeNu.frame = [ToolViewAndData MyAutoLayout:codeNu];
        view.frame = [ToolViewAndData MyAutoLayout:view];



    [view addSubview:codeNu];
    [self.view addSubview:view];
};
-(void)addtabelview{
    CGFloat tabelY =165;
    UITableView *tabel = [[UITableView alloc]initWithFrame:CGRectMake(0, tabelY, 320, 480) style:UITableViewStylePlain];
    _tabelView = tabel;
    tabel.frame = [ToolViewAndData MyAutoLayoutOnlyWidth:tabel];
    
    tabel.delegate = self;
    
    tabel.dataSource = self;
    
    [self.view addSubview:tabel];
    
};
//添加按钮
-(void)backBut{

//    JMReleaseStrVController *view = [[JMReleaseStrVController alloc] init];
//    [self.navigationController pushViewController:view animated:YES];
//    NSLog(@"fanghui");
    [self.navigationController popViewControllerAnimated:YES];

    
}
-(void)faut:(UIButton *)button{
    _fautBut.selected = YES;
    _winRateBut.selected = NO;
    _codeNuBut.selected = NO;

    NSString *strurl = [NSString stringWithFormat:@"%@%@&page=%@&pageSize=%@&Sort=%@",JMURLGetStrategyList,@"oxpDpszxtm69VMqWnPfPQLNhoQPbgHsWGgwBxoZ9EKW9qnu2XwS%2fJGfD2VFR3Kg3",@"1",@"2",@""];



    [self loadDatastrUrl:strurl];
    //    更新界面
    dispatch_async(dispatch_get_main_queue(), ^{
//        [_tabelView reloadData];
    });

}
-(void)winRate:(UIButton *)button{
    _fautBut.selected = NO;
    _winRateBut.selected = YES;
    _codeNuBut.selected = NO;

    NSString *strurl = [NSString stringWithFormat:@"%@%@&page=%@&pageSize=%@&Sort=%@",JMURLGetStrategyList,@"oxpDpszxtm69VMqWnPfPQLNhoQPbgHsWGgwBxoZ9EKW9qnu2XwS%2fJGfD2VFR3Kg3",@"1",@"3",@"rate_asc"];

    
    [self loadDatastrUrl:strurl];
    
    //    更新界面
    dispatch_async(dispatch_get_main_queue(), ^{
//        [_tabelView reloadData];
    });

}
-(void)codeNu:(UIButton *)button{
    _fautBut.selected = NO;
    _winRateBut.selected = NO;
    _codeNuBut.selected = YES;
    NSString *strurl = [NSString stringWithFormat:@"%@%@&page=%@&pageSize=%@&Sort=%@",JMURLGetStrategyList,@"oxpDpszxtm69VMqWnPfPQLNhoQPbgHsWGgwBxoZ9EKW9qnu2XwS%2fJGfD2VFR3Kg3",@"1",@"3",@"jindu_desc"];
    
    [self loadDatastrUrl:strurl];
    
    //    更新界面
    dispatch_async(dispatch_get_main_queue(), ^{
//        [_tabelView reloadData];
    });
    
}
//实现tabelview的代理方法和数据源方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Incomplete implementation, return the number of sections
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _robChips.count;
//    return 5;

}
//返回怎样的cell
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *ID = @"cell";
    JMGrabChipsCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (cell==nil) {
        cell = [[JMGrabChipsCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:ID];
        _GrabChipsCell = cell;
        _GrabChipsCell.voteBut.tag = 100 +indexPath.row;
        [ _GrabChipsCell.voteBut addTarget:self action:@selector(voteButClick:) forControlEvents:UIControlEventTouchUpInside];
        //    获取对应的行
        robChipModel *rob = _robChips[indexPath.row];
        //    添加数据¥
        //     姓名
        _GrabChipsCell.nameLabel.text = [NSString stringWithFormat:@"%@",rob.NickName];
        //    等级
         _GrabChipsCell.gradeLabel.text =[NSString stringWithFormat:@"等级：%@",rob.LevelName];
        
        int number =rob.Level;
         NSString *imagestr = [NSString stringWithFormat:@"%d",number];
        _GrabChipsCell.gradeNumLabel.text =[NSString stringWithFormat:@"%@",imagestr];

          // 胜率值
        _GrabChipsCell.winRateNumLabel.text =[NSString stringWithFormat:@"%d",rob.WinRate] ;
        
        // 计划编码
        _GrabChipsCell.planNoLabel.text =[NSString stringWithFormat:@"计划编码：%@",rob.StrategyNumber] ;
        
       int number1 =rob.PollYet;
        NSString *imagestr1 = [NSString stringWithFormat:@"%d",number1];
        // 已投人数数量
        _GrabChipsCell.PollYetNumLabel.text =[NSString stringWithFormat:@"%@",imagestr1] ;
        // 可投人总数
        _GrabChipsCell.PollPlanNumLabel.text =[NSString stringWithFormat:@"/%d",rob.PollPlan] ;
        
        
        _GrabChipsCell.progressView.trackTintColor=RGB(218, 218, 218);
        //设置进度默认值，这个相当于百分比，范围在0~1之间，不可以设置最大最小值
        float floatString =rob.PollYet*0.01;
        _GrabChipsCell.progressView.progress=floatString;
        //设置进度条上进度的颜色
       _GrabChipsCell.progressView.progressTintColor=RGB(240, 174, 32);
        //设置进度值并动画显示
        [_GrabChipsCell.progressView setProgress:floatString animated:YES];
        
    }
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    if (indexPath.row==0) {
        teamRankTVController *vc = [[teamRankTVController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }

    if (indexPath.row==1) {
        JMReleaseStrVController *view = [[JMReleaseStrVController alloc] init];
//        JMNavigationController *nav = [[JMNavigationController alloc]initWithRootViewController:view];
//        [nav pushViewController:view animated:YES];
        [self.navigationController pushViewController:view animated:YES];
        
    }

}
-(void)voteButClick:(UIButton*)voteBut{
    /**
     *  api/Strategy/StrategyPut?Token={Token}&StrategyId={StrategyId}
     */
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:(voteBut.tag - 100) inSection:0];
    _GrabChipsCell.voteBut.tag = 100 +indexPath.row;
    //    获取模型修改模型数据
    long row = voteBut.tag - 100;
    robChipModel *rob = _robChips[row];

     NSString *strurl = [NSString stringWithFormat:@"%@%@&StrategyId=%@",JMURLStrategyPut,@"nKMaAT8SPpV%2f7SukYU%2bfnnPI3xUf0tJtADGoHjhC865NtVWhCUg9RWats%2bYrOxUP",rob.Id];
    NSArray *arrayR = @[@"",strurl,@"GET"];
    [Request startRequestWithArray:arrayR FinishedBlock:^(NSData *data) {
        if (data) {
            //请求成功，解析json数据
            NSDictionary *datadict = [JMData dictAndTestData:data];
            //  字典转模型
            voteModel *robChip = [voteModel voteWithDict:datadict];
           //   判断投票情况
            if ([robChip.data intValue] == -6) {
                SHOWALERT(@"投票时间为8:00-8:50");
            }
            if ([robChip.data intValue] == -5) {
                SHOWALERT(@"投票总数超过预定票数");
            }
            if ([robChip.data intValue] == -4) {
                SHOWALERT(@"策略状态不可投票");
            }
            if ([robChip.data intValue] == -3) {
                SHOWALERT(@"已经投过该策略");
            }
            if ([robChip.data intValue] == -2) {
                SHOWALERT(@"松果等级不够");
            }
            if ([robChip.data intValue] == -1) {
                SHOWALERT(@"用户状态不对");
            }
            if ([robChip.data intValue] == 0) {
                SHOWALERT(@"失败");
            }
            if ([robChip.data intValue] == 1) {
    
           //    刷新数据
                [self refreshNewData];
            }
  
        }
    } FailBlock:^(NSString *string) {
        SHOWALERT(@"网络繁忙，请耐心等待...");

    }];

}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return NO;
}
//下拉刷新
-(void)setDonwRefresh{
    
    UIRefreshControl *fresh=[[UIRefreshControl alloc] init];
    _fresh = fresh;
    //
    [fresh addTarget:self action:@selector(addMoreDada) forControlEvents:UIControlEventValueChanged];
    [_tabelView addSubview:fresh];
    
    [self addMoreDada];
}
-(void)refreshNewData{
    
    if (_fautBut.selected) {
        
        [self faut:_fautBut];
        
        [_fresh endRefreshing];
    }
    if (_winRateBut.selected) {
        
        [self winRate:_winRateBut];
        
    }
    if (_codeNuBut.selected) {
        
        [self codeNu:_codeNuBut];
    }
//     1秒后刷新表格UI
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        // 刷新表格
    
        [_tabelView reloadData];
        
        });
}

-(void)addMoreDada{
//    刷新数据
    if (_fautBut.selected) {
        NSString *strurl = [NSString stringWithFormat:@"%@%@&page=%@&pageSize=%@&Sort=%@",JMURLGetStrategyList,@"oxpDpszxtm69VMqWnPfPQLNhoQPbgHsWGgwBxoZ9EKW9qnu2XwS%2fJGfD2VFR3Kg3",@"1",@"8",@""];
        
        [self loadDatastrUrl:strurl];
        
    }
    if (_winRateBut.selected) {
        
        NSString *strurl = [NSString stringWithFormat:@"%@%@&page=%@&pageSize=%@&Sort=%@",JMURLGetStrategyList,@"oxpDpszxtm69VMqWnPfPQLNhoQPbgHsWGgwBxoZ9EKW9qnu2XwS%2fJGfD2VFR3Kg3",@"1",@"15",@"rate_desc"];
        
        [self loadDatastrUrl:strurl];

    }
    if (_codeNuBut.selected) {
        
        NSString *strurl = [NSString stringWithFormat:@"%@%@&page=%@&pageSize=%@&Sort=%@",JMURLGetStrategyList,@"oxpDpszxtm69VMqWnPfPQLNhoQPbgHsWGgwBxoZ9EKW9qnu2XwS%2fJGfD2VFR3Kg3",@"1",@"10",@"jindu_desc"];
        
        [self loadDatastrUrl:strurl];

    }

      [_fresh endRefreshing];
}
//上拉加载
- (void)setupRefresh
{
    
//    _tabelView.tableFooterView = _footer;
//   _tabelView.footer = [_tabelView addFooterWithTarget:self action:@selector(loadMoreData)];

//    _tabelView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
//
//    // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadMoreData方法）
//    MJRefreshAutoGifFooter *footer = [MJRefreshAutoGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
//    // 设置尾部
//    _tabelView.footer = footer;
//    _footer = footer;
}
-(void)loadMoreData{
    //    刷新数据
    [self refreshNewData];
    //    结束刷新
//    [_footer endRefreshing];
}

@end
